import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class HelloServer {
    protected static int DEFAULT_PORT = 12345;
    protected int port;
    protected ServerSocket server;

    public HelloServer() throws InvalidPortNumberException {
        this(DEFAULT_PORT);
    }

    public HelloServer(int port) throws InvalidPortNumberException {
        validatePort(port);
        this.port = port;
    }
    public boolean isRunning(){
        return (this.server == null ) ? false : !this.server.isClosed();
    }

    public int getPort(){
        return this.port;
    }

    public void setPort(int port) throws InvalidPortNumberException {
        validatePort(port);
        this.port = port;
    }

    public void start() throws IOException {
        Socket socket;
        PrintWriter out;

        this.server = new ServerSocket(port);
        socket = this.server.accept();
        out = new PrintWriter(socket.getOutputStream(), true);
        out.println("Hello!");

        socket.close();
    }

    public void stop() throws IOException {
        this.server.close();
    }

    private void validatePort(int port) throws InvalidPortNumberException {
        if ( port < 0 || port > 65535) {
            throw new InvalidPortNumberException();
        }
    }
}
